#include<iostream>

using std::cout;
using std::endl;
#include <fcntl.h>           /* For O_* constants */
#include <sys/stat.h>        /* For mode constants */
#include <semaphore.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <iostream>


#define FILE_MODE S_IRUSR|S_IWUSR

int count = 0;

#include <unistd.h>
int main(int argc, char** argv)
{
    int i, nloop;
    
    if(argc != 2){
        cout << "usage: incr1 <#loops>" << endl;
        exit(-1);
    }
    nloop = atoi(argv[1]);
    
    sem_t* mutex = sem_open("/my_sem", O_CREAT|O_EXCL, FILE_MODE, 1);
    sem_unlink("/my_sem");
    

    setbuf(stdout, NULL);
    
    if(fork() == 0){
        for( int i = 0; i < nloop; ++i){
            sem_wait(mutex);
            cout << "child: " << count++ << endl;
            sem_post(mutex);
        }
        exit(0);
    }
    for( int i = 0; i < nloop; ++i){
        sem_wait(mutex);
        cout << "parent: " << count++ << endl;
        sem_post(mutex);
    }
    exit(0);
    
}

